<template>
  <view class="arrears-type-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">欠费类型统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
              <text class="filter-label">停车场：</text>
              <picker :value="filters.parkingLotIndex" :range="parkingLotOptions" @change="onParkingLotChange">
                <view class="date-picker">
                  <text>{{ filters.parkingLotIndex >= 0 ? parkingLotOptions[filters.parkingLotIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">欠费类型：</text>
              <picker :value="filters.arrearsTypeIndex" :range="arrearsTypeOptions" @change="onArrearsTypeChange">
                <view class="date-picker">
                  <text>{{ filters.arrearsTypeIndex >= 0 ? arrearsTypeOptions[filters.arrearsTypeIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">车牌号</text>
          <text class="list-cell">车辆数量</text>
          <text class="list-cell">占比</text>
          <text class="list-cell">欠费总额</text>
          <text class="list-cell">平均欠费</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="showDetail(item)">
        <text class="list-cell">{{ item.licensePlate }}</text>
        <text class="list-cell">{{ item.vehicleCount }}</text>
        <text class="list-cell">{{ item.percentage }}%</text>
        <text class="list-cell">{{ item.totalAmount }}元</text>
        <text class="list-cell">{{ item.averageAmount }}元</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">详情信息</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">车牌号：</text>
            <text class="detail-value">{{ currentDetail.licensePlate }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">欠费类型：</text>
            <text class="detail-value">{{ currentDetail.arrearsType }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占比：</text>
            <text class="detail-value">{{ currentDetail.percentage }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">欠费总额：</text>
            <text class="detail-value">{{ currentDetail.totalAmount }}元</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均欠费：</text>
            <text class="detail-value">{{ currentDetail.averageAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.arrearsType !== '无欠费车辆' && currentDetail.arrearsType !== '无消费记录车牌'">
            <text class="detail-label">最高欠费：</text>
            <text class="detail-value">{{ currentDetail.maxAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.arrearsType !== '无欠费车辆' && currentDetail.arrearsType !== '无消费记录车牌'">
            <text class="detail-label">最低欠费：</text>
            <text class="detail-value">{{ currentDetail.minAmount }}元</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.arrearsType === '短期欠费车辆' || currentDetail.arrearsType === '长期欠费车辆'">
            <text class="detail-label">平均欠费天数：</text>
            <text class="detail-value">{{ currentDetail.avgArrearsDays }}天</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'

// 筛选条件
const filters = reactive({
  periodIndex: 0,
  parkingLotIndex: -1,
  arrearsTypeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 停车场选项
const parkingLotOptions = [
  '全部',
  'A区停车场',
  'B区停车场',
  'C区停车场',
  'D区停车场'
]

// 欠费类型选项
const arrearsTypeOptions = [
  '全部',
  '无欠费车辆',
  '短期欠费车辆',
  '长期欠费车辆',
  '无消费记录车牌'
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 停车场选择处理
const onParkingLotChange = (e) => {
  filters.parkingLotIndex = parseInt(e.detail.value)
}

// 欠费类型选择处理
const onArrearsTypeChange = (e) => {
  filters.arrearsTypeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.parkingLotIndex = -1
  filters.arrearsTypeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
  }, 500)
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 定义欠费类型
  const arrearsTypes = [
    '无欠费车辆',
    '短期欠费车辆',
    '长期欠费车辆',
    '无消费记录车牌'
  ]
  
  // 停车场列表
  const parkingLots = parkingLotOptions.slice(1) // 排除"全部"选项
  
  // 生成随机车牌号的函数
  const generateLicensePlate = () => {
    const provinces = ['京', '沪', '粤', '苏', '浙', '鲁', '豫', '川', '渝', '陕']
    const letters = 'ABCDEFGHJKLMNPQRSTUVWXYZ'
    const numbers = '0123456789'
    
    const province = provinces[Math.floor(Math.random() * provinces.length)]
    const letter = letters[Math.floor(Math.random() * letters.length)]
    
    let plate = province + letter
    
    // 生成5位数字和字母组合
    for (let i = 0; i < 5; i++) {
      if (Math.random() > 0.7) { // 30%概率使用字母
        plate += letters[Math.floor(Math.random() * letters.length)]
      } else { // 70%概率使用数字
        plate += numbers[Math.floor(Math.random() * numbers.length)]
      }
    }
    
    return plate
  }
  
  // 计算总车辆数（用于计算占比）
  const totalVehicles = Math.floor(Math.random() * 1000) + 2000 // 2000-3000
  let remainingVehicles = totalVehicles
  
  // 根据筛选条件确定要生成的欠费类型
  let typesToGenerate = []
  if (filters.arrearsTypeIndex <= 0) {
    // 全部类型
    typesToGenerate = [...arrearsTypes]
  } else {
    // 选择了特定类型
    typesToGenerate = [arrearsTypeOptions[filters.arrearsTypeIndex]]
  }
  
  // 生成随机数据
  for (let i = 0; i < typesToGenerate.length; i++) {
    const currentType = typesToGenerate[i]
    const typeIndex = arrearsTypes.indexOf(currentType)
    
    // 根据欠费类型确定要生成的车辆数量
    let vehicleCount
    if (typesToGenerate.length === 1) {
      // 如果只选择了一种类型，则使用全部车辆数
      vehicleCount = totalVehicles
    } else if (i === typesToGenerate.length - 1) {
      // 最后一个类型使用剩余车辆数
      vehicleCount = remainingVehicles
    } else {
      // 根据欠费类型设置不同的车辆数量分布
      let percentage
      if (currentType === '无欠费车辆') {
        percentage = Math.random() * 0.2 + 0.5 // 50%-70%
      } else if (currentType === '短期欠费车辆') {
        percentage = Math.random() * 0.1 + 0.1 // 10%-20%
      } else if (currentType === '长期欠费车辆') {
        percentage = Math.random() * 0.05 + 0.05 // 5%-10%
      } else { // 无消费记录车牌
        percentage = Math.random() * 0.05 + 0.05 // 5%-10%
      }
      vehicleCount = Math.floor(totalVehicles * percentage)
      remainingVehicles -= vehicleCount
    }
    
    // 为每种类型生成多个车牌号数据
    const vehiclesPerPage = Math.min(vehicleCount, pageSize)
    const startIndex = (pageNo - 1) * pageSize
    
    // 计算当前页应显示的车辆数
    const pageVehicleCount = Math.min(vehiclesPerPage, vehicleCount - startIndex)
    
    // 如果当前页没有数据，跳过
    if (pageVehicleCount <= 0) continue
    
    // 计算每辆车的占比
    const singleVehiclePercentage = ((1 / vehicleCount) * 100).toFixed(2)
    
    // 生成欠费金额（根据欠费类型设置不同的金额范围）
    let totalAmount = 0
    let averageAmount = 0
    let maxAmount = 0
    let minAmount = 0
    let avgArrearsDays = 0
    
    if (currentType === '短期欠费车辆') {
      // 短期欠费（1-30天）
      averageAmount = Math.floor(Math.random() * 50) + 20 // 20-70元
      totalAmount = averageAmount.toFixed(2)
      maxAmount = Math.floor(averageAmount * (1 + Math.random() * 0.5)) // 最高上浮50%
      minAmount = Math.floor(averageAmount * (1 - Math.random() * 0.3)) // 最低下浮30%
      avgArrearsDays = Math.floor(Math.random() * 15) + 5 // 5-20天
    } else if (currentType === '长期欠费车辆') {
      // 长期欠费（30天以上）
      averageAmount = Math.floor(Math.random() * 150) + 100 // 100-250元
      totalAmount = averageAmount.toFixed(2)
      maxAmount = Math.floor(averageAmount * (1 + Math.random() * 1)) // 最高上浮100%
      minAmount = Math.floor(averageAmount * (1 - Math.random() * 0.2)) // 最低下浮20%
      avgArrearsDays = Math.floor(Math.random() * 60) + 30 // 30-90天
    } else {
      // 无欠费或无消费记录
      totalAmount = '0.00'
      averageAmount = '0.00'
    }
    
    // 随机选择停车场
    const selectedParkingLotIndex = filters.parkingLotIndex > 0 
      ? filters.parkingLotIndex - 1 
      : Math.floor(Math.random() * parkingLots.length)
    const parkingLot = parkingLots[selectedParkingLotIndex]
    
    // 生成当前页的车牌数据
    for (let j = 0; j < pageVehicleCount; j++) {
      data.push({
        id: startIndex + j + 1,
        licensePlate: generateLicensePlate(),
        arrearsType: currentType,
        vehicleCount: 1,
        percentage: singleVehiclePercentage,
        totalAmount,
        averageAmount,
        maxAmount,
        minAmount,
        avgArrearsDays,
        parkingLot
      })
    }
  }
  
  return data
}

// 显示详情
const showDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.arrears-type-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.list-header {
  display: flex;
  background: #f0f0f0;
  padding: 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx 10rpx 0 0;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.list-row {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 26rpx;
  color: #666;
  
  &:last-child {
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}
</style>